<template>
  <section class="f-transfer">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">调拨单列表</span>
      </div>
      <div class="my-search-box">
        <div>
          <span>调拨ID：</span>
          <el-input v-model="searchForm.recordId" clearable placeholder="请输入调拨ID" />
        </div>
        <div>
          <span>订单号：</span>
          <el-input v-model="searchForm.orderId" clearable placeholder="请输入订单号" />
        </div>
        <div>
          <span>状态：</span>
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="待处理" value="0" />
            <el-option label="部分调拨" value="1" />
            <el-option label="已完成" value="2" />
            <el-option label="已关闭" value="3" />
          </el-select>
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe>
          <el-table-column type="expand">
            <template #default="props">
              <el-table :data="props.row.children" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
                :cell-style="{fontSize:'12px',color:'#7b7b7d'}" style="width: 600px;margin-left: 60px">
                <el-table-column type="index" width="55" label="序号" align="center" />
                <el-table-column label="调拨ID" prop="recordChildrenId" align="center" />
                <el-table-column label="型号" prop="equipmentType" align="center" />
                <el-table-column label="颜色" prop="color" align="center" width="100" />
                <el-table-column label="总数" prop="total" align="center" width="100" />
                <el-table-column label="已调拨数" prop="diaoboNum" align="center" width="100" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="recordId" label="调拨ID" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary" @click="openDialog(2,scope.row)">
                {{ scope.row.recordId || '--' }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="orderId" label="订单号" align="center">
            <template v-slot="scope">
              {{ scope.row.orderId || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="shopName" label="代理商" align="center">
            <template v-slot="scope">
              {{ scope.row.shopName || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="total" label="总数" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.total }}
            </template>
          </el-table-column>
          <el-table-column prop="diaoboNum" label="已调拨" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.diaoboNum  }}
            </template>
          </el-table-column>
          <el-table-column prop="type" label="业务类型" align="center" width="90">
            <template v-slot="scope">
              {{ scope.row.type == 1? '代理商下单': scope.row.type == 2? '管理端调拨': '--'}}
            </template>
          </el-table-column>
          <el-table-column prop="actionType" label="调拨类型" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.actionType == 1? '不发货': scope.row.actionType == 2? '发货': '--'}}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="80">
            <template v-slot="scope">
              {{ status[scope.row.status]  }}
            </template>
          </el-table-column>
          <el-table-column label="收货人信息" align="center" min-width="120">
            <template v-slot="scope">
              <p>收件人： {{ scope.row.receiveName  || '--'}}</p>
              <p>联系电话： {{ scope.row.receivePhone  || '--'}}</p>
              <p>收获地址： {{ scope.row.receiveAddressDetail  || '--'}}</p>
            </template>
          </el-table-column>
          <el-table-column label="物流信息" align="center">
            <template v-slot="scope">
              <p>物流单号： {{ scope.row.logisticsNum  || '--'}}</p>
              <p>物流公司： {{ scope.row.logisticsName  || '--'}}</p>
            </template>
          </el-table-column>
          <el-table-column label="更新信息" align="center">
            <template v-slot="scope">
              <p>{{ scope.row.modifyByUserName|| '--' }}</p>
              <p>{{ getDateTime(scope.row.modifyTimeMill)[6] || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column label="创建信息" align="center">
            <template v-slot="scope">
              <p>{{ scope.row.createByUserName|| '--' }}</p>
              <p>{{ getDateTime(scope.row.createTimeMill)[6] || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link v-if="scope.row.status != 2" style="font-size:12px" type="primary"
                  @click="importHandle(scope.row)">导入</el-link>
                <el-link v-if="scope.row.status != 2" style="font-size:12px" type="primary"
                  @click="openDialog(1,scope.row)">调拨</el-link>
                <el-link v-if="scope.row.status == 0" style="font-size:12px" type="danger"
                  @click="settingHandle(scope.row)">取消</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" apiName="diaoboImportTemplate"
      @handleUploadSuccess="importSuccess" @handleUploadCancel="handleUploadCancel">
      <template #slotForm="parent">
        <el-form-item label="物流单号" label-width="100">
          <el-input v-model="parent.formData.data.logisticsNum" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="物流公司" label-width="100">
          <el-input v-model="parent.formData.data.logisticsName" placeholder="请输入物流公司" />
        </el-form-item>
      </template>
    </Upload>

    <!-- 确认密码 -->
    <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />

    <el-dialog v-model="dialogTableVisible" title="调拨详情" width="900">
      <div class="my-table-box">
        <el-table height="500" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="dialogTable" stripe>
          <el-table-column type="expand">
            <template #default="props">
              <el-table :data="props.row.list" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
                :cell-style="{fontSize:'12px',color:'#7b7b7d'}" style="width: 400px;margin-left: 60px">
                <el-table-column type="index" width="55" label="序号" align="center" />
                <el-table-column label="设备ID" prop="deviceId" align="center" />
                <el-table-column label="设备编号" prop="deviceNo" align="center" />
              </el-table>
            </template>
          </el-table-column>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="recordChildrenId" label="调拨ID" align="center">
            <template v-slot="scope">
              {{ scope.row.recordChildrenId || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="wareGoodsId" label="设备商品ID" align="center">
            <template v-slot="scope">
              {{ scope.row.wareGoodsId }}
            </template>
          </el-table-column>
          <el-table-column prop="equipmentType" label="型号" align="center">
            <template v-slot="scope">
              {{ scope.row.equipmentType }}
            </template>
          </el-table-column>
          <el-table-column prop="color" label="颜色" align="center">
            <template v-slot="scope">
              {{ scope.row.color }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="exportHandle()">导出</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 调拨弹窗 -->
    <el-dialog v-model="dialogVisible" title="设备调拨" width="720" top="2vh">
      <p class="f-tips">设备ID和设备编号不能同时为空，如果同时存在以设备ID为准</p>
      <el-form class="f-form-box " ref="dialogFormRef" :model="dialogForm" :rules="dialogRules" :inline="true">
        <el-form-item label="物流单号">
          <el-input v-model="dialogForm.logisticsNum" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="物流公司">
          <el-input v-model="dialogForm.logisticsName" placeholder="请输入物流公司" />
        </el-form-item>
        <template v-for="(item,index) in dialogForm.children" :key="item.orderId">
          <ul class="f-ul">
            <li>
              <span>设备型号：</span>
              <span>{{ item.equipmentType }}</span>
            </li>
            <li>
              <span>设备颜色：</span>
              <span>{{ item.color }}</span>
            </li>
            <li>
              <span>总数：</span>
              <span>{{ item.total }}</span>
            </li>
            <li>
              <span>已调拨数：</span>
              <span>{{ item.diaoboNum }}</span>
            </li>
          </ul>

          <el-transfer v-model="item.selectList" filterable :props="{key: 'deviceId',label: 'deviceNo'}"
            :data="warehouseMap[item.wareGoodsId]" @change="handleWarehouse($event,index)" />
        </template>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel()">取消</el-button>
          <el-button type="primary" @click="dialogSave()">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import ConfirmPass from '@/components/confirmPass.vue'
import api from '../api'

export default {
  components: { Upload, ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)
    const confirmPasswordRef = ref(null)
    const dialogFormRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
      },
      isDetail: false,

      searchForm: {
        "createTimeMax": "",
        "createTimeMin": "",
        "orderBy": "id desc",
        "orderId": "",
        "recordId": "",
        "shopId": "",
        "showChildren": "1", // 是否返回子单数据，1-是 0-否
        "status": "" // 状态，0-待处理，1-部分调拨，2-已完成
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      uploadForm: {
        dialogTitle: '导入调拨内容',
        action: '/eas/manage/yilian/diaobo/importData',
        recordId: ''
      },

      status: {
        '0': '待处理',
        '1': '部分调拨',
        '2': '已完成',
        '3': '已关闭',
      },

      uniqueId: '',
      dialogTableVisible: false,
      dialogTable: [],

      dialogVisible: false,
      dialogForm: {},
      dialogRules: {
        logisticsNum: [
          { required: true, message: '请输入物流单号', trigger: 'blur' },
        ],
        logisticsName: [
          { required: true, message: '请输入物流公司', trigger: 'blur' },
        ],
      },

      warehouseList: [],
      warehouseSelect: [],
      warehouseMap: {},
      confirmData: {}
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/inventoryTransfer')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "createTimeMax": "",
        "createTimeMin": "",
        "orderBy": "id desc",
        "orderId": "",
        "recordId": "",
        "shopId": "",
        "showChildren": "1", // 是否返回子单数据，1-是 0-否
        "status": "" // 状态，0-待处理，1-部分调拨，2-已完成
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.transferList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    // 导出
    const exportHandle = () => {
      const obj = {
        responseType: 'blob',
        uniqueId: state.uniqueId
      }
      api.transferExport(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
        warningDeal('导出失败！')
      })
    }

    // 导入
    function importHandle(data) {
      state.off.upload = true
      state.uploadForm.recordId = data.recordId
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    const handleUploadCancel = () => {
      state.off.upload = false
    }

    function settingHandle(data) {
      state.confirmData = data
      const title = "取消提示"
      const msg = '您确定要将所选调拨单取消吗？'
      confirmPasswordRef.value.dialogShow(title, msg)
    }

    const confirmSuccess = () => {
      let json = {
        uniqueId: state.confirmData.recordId
      }
      api.transferDelete(json).then(res => {
        successDeal('操作成功！')
        getTableData()
      })
    }

    const openDialog = (type, data) => {
      if (type == 1) {
        state.warehouseList = []
        state.dialogVisible = true
        state.dialogForm = JSON.parse(JSON.stringify(data))
        data.children.forEach(item => {
          getWarehouseInfoList(item)
        })
      } else if (type == 2) {
        state.dialogTableVisible = true
        state.uniqueId = data.recordId
        let json = {
          "orderBy": "id desc",
          "page": 1,
          "size": 100,
          "uniqueId": data.recordId
        }
        api.transferDeviceDetail(json).then(res => {
          state.dialogTable = res.data.list
        })
      }
    }

    const strategyAdd = (data, index) => {
      let obj = {
        "deviceId": "",
        "deviceNo": "",
        "recordChildrenId": data.recordChildrenId
      }
      if (data.list) {
        data.list.push(obj)
      } else {
        data.list = []
        data.list.push(obj)
      }
    }

    const strategyDelete = (data, index) => {
      data.list.splice(index, 1)
    }

    const dialogCancel = () => {
      state.dialogVisible = false
      state.dialogForm = {}
      dialogFormRef.value.resetFields()
    }

    const dialogSave = () => {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = {
            "list": [],
            logisticsNum: state.dialogForm.logisticsNum,
            logisticsName: state.dialogForm.logisticsName,
          }
          state.dialogForm.children.forEach((item, index) => {
            if (item.selectList?.length) {
              let arr = state.warehouseMap[item.wareGoodsId]
              let list = arr.filter(item1 => item.selectList.includes(item1.deviceId))
              list.forEach(myItem => {
                let obj = {
                  "deviceId": myItem.deviceId,
                  "deviceNo": myItem.deviceNo,
                  "recordChildrenId": item.recordChildrenId
                }
                json.list.push(obj)
              })
            }
          })
          api.transferSubmit(json).then(res => {
            successDeal('操作成功！')
            getTableData()
            dialogCancel()
          })
        }
      })
    }

    const getWarehouseInfoList = (data) => {
      let json = {
        wareGoodsId: data.wareGoodsId,
        page: 1,
        size: 100,
        saled: "0"
      }
      api.warehouseInfoList(json).then(res => {
        state.warehouseList.push(res.data.list)
        // state.warehouseMap.set(res.data.list[0].wareGoodsId, res.data.list)
        state.warehouseMap[res.data.list[0].wareGoodsId] = res.data.list
      })
    }

    const handleWarehouse = (e, index) => {
      console.log(e, index)
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 270
      setIsDetail()
    })

    return {
      ...toRefs(state),
      uploadRef,
      confirmPasswordRef,
      dialogFormRef,
      searchHandle,
      resetHandle,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      exportHandle,
      importSuccess,
      importHandle,
      handleUploadCancel,
      settingHandle,
      confirmSuccess,
      openDialog,
      strategyAdd,
      strategyDelete,
      dialogCancel,
      dialogSave,
      handleWarehouse,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-transfer {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    > .title-box {
      display: flex;
      align-items: center;

      > .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0 15px;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
  .f-strategy-box {
    width: 100%;
    border: 1px solid #d6dee5;
    .f-strategy-header {
      height: 44px;
      background: #d6dee5;
      display: flex;
      align-items: center;
      padding: 0 16px;
    }
    .f-strategy-body {
      li {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        padding: 10px 5px 10px 10px;
      }
    }
  }
  .f-divider {
    width: 100%;
    height: 1px;
    background: #d6dee5;
  }
  .f-ul {
    display: flex;
    align-items: center;
    gap: 0 30px;
    margin-bottom: 20px;
    font-size: 14px;
    font-weight: bold;
    color: #606266;
    li {
      display: flex;
      align-items: center;
      span:last-child {
        color: #000000;
      }
    }
  }
  .f-ul:not(:first-child) {
    margin-top: 30px;
  }
  .f-tips {
    background-color: rgba(230, 162, 60, 0.8);
    color: #ffffff;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 5px 10px;
    border-radius: 5px;
    font-size: 12px;
    margin-bottom: 20px;
  }
  .f-form-box {
    background-color: rgba(24, 144, 255, 0.1);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    padding: 20px;
    border-radius: 5px;
    margin-top: 10px;
  }
  :deep(.el-transfer-panel) {
    width: 230px;
  }
}
</style>

<style lang="scss" >
.el-transfer-panel
  .el-transfer-panel__header
  .el-checkbox
  .el-checkbox__label
  span {
  display: none;
}
</style>